package com.swak.boot.config.job;

import java.util.Set;

import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;

import com.swak.annotation.Job;
import com.swak.boot.ApplicationBooter;
import com.swak.job.JobService;
import com.swak.utils.Sets;

/**
 * 消费者启动
 * 
 * @author lifeng
 */
public class JobPostProcessor implements BeanPostProcessor, ApplicationBooter {

	private final Set<Object> jobBeans = Sets.newHashSet();
	private JobService jobService;

	/**
	 * 保留JobService对象
	 */
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		Class<?> clazz = bean.getClass();
		if (clazz.isAssignableFrom(JobService.class)) {
			jobService = (JobService) bean;
			return bean;
		}
		return bean;
	}

	/**
	 * 初始化结束之后注册 -- 只需要找到一个即可
	 */
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		Class<?> clazz = bean.getClass();
		if (AopUtils.isAopProxy(bean)) {
			clazz = AopUtils.getTargetClass(bean);
		}
		if (clazz.getAnnotation(Job.class) != null) {
			jobBeans.add(bean);
		}
		return bean;
	}

	/**
	 * 注意： <br>
	 * 1. 如果是服务器环境则需要等待服务器启动之后再初始化其他组件<br>
	 * 2. 如果是应用环境则可以直接启动<br>
	 * 
	 * @param context
	 */
	@Override
	public void onApplicationEvent(ApplicationContext context) {
		if (jobService != null) {
			jobService.start(jobBeans);
		}
	}
}